<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\model;

use app\admin\logic\Trash;
use think\Db;

/**
 * 会员余额模型
 */
class UserAccount extends ModelBase
{

    protected $insert = ['create_time'];


    /**
     * 自动添加钱包
     */
    public static function check($where,$true=true){
        if (!EthAccount::get([ 'user_id'=>$where['user_id']])) {
            EthAccount::create([ 'user_id'=>$where['user_id']]);
        }
        $info=self::where($where)->lock(true)->find();
       if ($info){
           return $info;
       }else{
           $data=[
               'user_id'=>$where['user_id'],
               'wallet_id'=>$where['wallet_id'],
           ];
           switch ($where['wallet_id']){
               case 6:

                    $address2=CoinAddress::where(['status'=>0,'mid'=>6])->order('id asc')->find();
                    if( $address2){

                        $data['blockchain_address2']=$address2['address'];
                        $address2->status=1;
                        $address2->save();
                    }
                    break;
                case 7:
                    $address2=CoinAddress::where(['status'=>0,'mid'=>7])->order('id asc')->find();
                    if(  $address2){

                        $data['blockchain_address2']=$address2['address'];
                        $address2->status=1;
                        $address2->save();
                    }
                    break;
                case 8:
                    $address2=self::where(['user_id'=>$where['user_id'],'wallet_id'=>7])->value('blockchain_address2');
                    if(  $address2){
                        $data['blockchain_address2']=$address2;
                    }
                    break;
               default:

                   break;
           }
           $id=self::create($data);
           if(!$true){
               $info=self::where(['id'=>$id->id])->lock(true)->find();
           }else{
               $info=self::where(['id'=>$id->id])->lock(true)->find();
           }
           return $info;
       }

    }

    /**
     * 连用户表
     */
    public function member(){
        return $this->belongsTo('Member','user_id','id');
    }


    /**
     * 连钱包表
     */
    public function wallet(){
        return $this->belongsTo('Wallet','wallet_id','id');
    }

    /**
     * 自动添加钱包
     */
    public static function addWallet($uid){
        EthAccount::create(['user_id'=>$uid]);
        $wallet=\think\Db::name('wallet')->where(['is_virtual'=>1])->select();
        //$wallet=get_wallet_list();
        if($wallet){
            foreach ($wallet as $k=>$v){
                    $data=[ 'user_id'=>$uid,
                        'wallet_id'=>$v['id'],
//                        'wallet_address'=>get_wetoken_url()
                        ];
                    if($v['is_currency']==1){
                        $data['is_wallet']=2;
                        switch ($v['id']){
                            case 6:

                                $address2=CoinAddress::where(['status'=>0,'mid'=>6,'type'=>0])->order('id asc')->find();
                                if(  $address2){
                                    $data['blockchain_address2']=$address2['address'];
                                    $address2->status=1;
                                    $address2->save();
                                }
                                break;
                            case 7:
                                $address2=CoinAddress::where(['status'=>0,'mid'=>7,'type'=>0])->order('id asc')->find();
                                if(  $address2){

                                    $data['blockchain_address2']=$address2['address'];

                                    $address2->status=1;

                                    $address2->save();
                                }
                                break;
                            case 8: //USDT改成ETH代币

                                $address2=self::where(['user_id'=>$uid,'wallet_id'=>6])->value('blockchain_address2');
                                if(  $address2){
                                    $data['blockchain_address2']=$address2;
                                }
                                break;
                            
                        }

                    }
                    self::create($data);

            }
        }

    }

    /**
     * 自动检测钱包
     */
    public static function checkWallet($uid){
        $wallet=Wallet::where(['status'=>1,'is_virtual'=>1])->select();

        if($wallet){
            foreach ($wallet as $k=>$v){
                if(!UserAccount::get([ 'user_id'=>$uid, 'wallet_id'=>$v['id']])){
                    $data=[ 'user_id'=>$uid,
                        'wallet_id'=>$v['id'],
//                        'wallet_address'=>get_wetoken_url(),
                    ];

                    if($v['is_currency']==1){
                        $data['is_wallet']=2;
                        switch ($v['id']){
                            case 6:
                              //  $address=CoinAddress::where(['status'=>0,'mid'=>6])->order('id desc')->find();
                                $address2=CoinAddress::where(['status'=>0,'mid'=>6,'type'=>0])->order('id asc')->find();
                                if($address2){
                                //    $data['blockchain_address']=$address['address'];
                                    $data['blockchain_address2']=$address2['address'];
                              //      $address->status=1;
                                    $address2->status=1;
                             //       $address->save();
                                    $address2->save();
                                }
                                break;
                            case 7:
                              //  $address=CoinAddress::where(['status'=>0,'mid'=>7])->order('id desc')->find();
                                $address2=CoinAddress::where(['status'=>0,'mid'=>7,'type'=>0])->order('id asc')->find();
                                if( $address2){
                              //      $data['blockchain_address']=$address['address'];
                                    $data['blockchain_address2']=$address2['address'];
                               //     $address->status=1;
                                    $address2->status=1;
                               //     $address->save();
                                    $address2->save();
                                }
                                break;
                            case 8: //USDT改成ETH代币
                              //  $address=self::where(['user_id'=>$uid,'wallet_id'=>7])->value('blockchain_address');
                                $address2=self::where(['user_id'=>$uid,'wallet_id'=>6])->value('blockchain_address2');
                                if(  $address2){
                                //    $data['blockchain_address']=$address;
                                    $data['blockchain_address2']=$address2;
                                }
                                break;
                        }




                    }
                    self::create($data);

                }
            }
        }

    }

    /**
     * logo
     */
    public function getBalanceAttr($value)
    {
        if(in_array($this->wallet_id,[1,2,3,4,5,9])){
            return  sprintf("%.2f",$value);
        }else{
            return $value;
        }
    }

    /**
     * logo
     */
    public function getFreezeBalanceAttr($value)
    {
        if(in_array($this->wallet_id,[1,2,3,4,5,9])){
            return  sprintf("%.2f",$value);
        }else{
            return $value;
        }
    }
    /**
     * 时间自动完成
     */
    public function setCreateTimeAttr($value)
    {

        return TIME_NOW;
    }


    //团队奖奖励
    public function share_reward($info){
        //团队奖奖励
        if ( $this->member->leader_id) {
            //获取代数奖励配置

            $dai =1;  //初始代数
            $dai_member = explode(',', substr($this->member->path, 0, strlen($this->member->path) - 1));  //总代数
            array_shift($dai_member);   //去掉自己

            $money=$info['reward_money'] ;
            
            foreach ($dai_member as $k=>$v){
                if($dai>10){
                    break;
                }
                $member=Member::get($v);
                $level=$member->level;
                $reward=0;
                if($level['id']==8 && $member['level_id']==8){
                    $reward=$level['reward'];
                    $msg=$this->member['username'].'给我返平级奖';
                    $is_same=1;
                }else{


                    $share_json=json_decode($level->share_json,true);

                    if( $dai<=$share_json[0]['level'] ){
                        $reward=$share_json[0]['reward'][$dai-1];
                        $msg=$this->member['username'].'给我返第'.$dai.'代团队奖';
                    }
                    $is_same=0;

                }

                if($reward>0){
                    $leader_account=self::check(['user_id'=>$v,'wallet_id'=>3],false);
                    $algebra_money =format_money($money *$reward / 100,2);
                    if($algebra_money>=0.01){
                        if($leader_account->member->level['share_reward_max']>0){
                            //今天已获得分享奖
                            $today_money=UserAccountLog::where(['create_time'=>['between',[getTodayStart(),getTodayEnd()]],'user_id'=>$leader_account['user_id'],'type'=>12])->sum('number');
                            if($today_money>=$leader_account->member->level['share_reward_max']){
                                //超过没日最大上限
                                continue;
                            }
                            if($today_money+$algebra_money>$leader_account->member->level['share_reward_max']){
                                $algebra_money=$leader_account->member->level['share_reward_max']-$today_money;
                            }

                        }

                        $leader_account->balance += $algebra_money;
                        $leader_account->save();
                        //写入代数奖流水
                        UserAccountLog::create([
                            'user_id' => $leader_account->user_id,
                            'number' => $algebra_money,
                            'wallet_id' => $leader_account['wallet_id'],
                            'before_blance' => $leader_account->balance - $algebra_money,
                            'after_blance' => $leader_account->balance,
                            'is_add' => 1,
                            'type' => $is_same==1?11:12,
                            'level_id' =>  $member->level_id,
                            'is_reward'=>1,
                            'uid'=>$this->user_id,
                            'algebra'=>$dai,
                            'remark' =>$msg,
                        ]);
                        Db::name("member")->where(["id"=>$leader_account->user_id])->setInc("bets_total_balance",$algebra_money);
                        user_notice($leader_account->user_id,$msg.'：'.$algebra_money);

                        $dai++;
                    }

                }




            }








        }
    }













    public function getTeamReward($list,$money){
        rsort($list);
        $reward=0;
        foreach ($list as $ke =>$va){
            if($money >$va['money']){
                $reward=$va['reward'];
                break;
            }
        }
        return $reward;
    }



}
